package com.glodon.paas.document.dao.mysql;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.glodon.paas.document.constant.DocumentConstant;
import com.glodon.paas.document.dao.ShareDao;
import com.glodon.paas.document.dao.domain.ShareEntity;
import com.glodon.paas.document.dao.mapper.ShareEntityMapper;

public class ShareDaoMysqlImpl implements ShareDao {

    int               startIndex = 0;
    int               count      = 100;
    @Autowired
    ShareEntityMapper shareEntityMapper;

    @Override
    public String insert(ShareEntity entity) {
        shareEntityMapper.insertSelective(entity);
        return entity.getId();
    }

    @Override
    public ShareEntity get(String id) {
        return shareEntityMapper.selectByPrimaryKey(id);
    }

    @Override
    public int delete(String id) {
        return shareEntityMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<ShareEntity> getShareForMe(String userId, String fileId) {
        List<ShareEntity> list = shareEntityMapper.selectShareForMe(userId, fileId, null, startIndex, count);
        return list;
    }

    @Override
    public List<ShareEntity> getShareByMe(String userId, String fileId, Integer shareType) {
        return shareEntityMapper.selectShareByMe(userId, fileId, shareType, startIndex, count);
    }

    @Override
    public boolean isSharedFile(String fileId) {
        return this.getShareCount(fileId, DocumentConstant.SHARE_TYPE_SHARED) > 0;
    }

    @Override
    public long getShareCount(String fileId, Integer shareType) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("fileId", fileId);
        param.put("shareType", shareType);
        long rt = shareEntityMapper.countBySelective(param);
        return rt;
    }

    @Override
    public void deleteByFile(String fileId, Integer shareType) {
        shareEntityMapper.deleteByFileId(fileId, shareType);
    }

    @Override
    public void deleteByOwner(String ownerId) {
        shareEntityMapper.deleteByOwnerId(ownerId);
    }

    @Override
    public boolean isPublishedFile(String fileId) {
        return this.getShareCount(fileId, DocumentConstant.SHARE_TYPE_PUBLISHED) > 0;
    }
    
    public void setShareEntityMapper(ShareEntityMapper shareEntityMapper) {
        this.shareEntityMapper = shareEntityMapper;
    }
}
